import com.rombo.hiberdemo.po.UserPO;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * Create by Yet on 2016/12/7
 **/
public class Main {
    private static final SessionFactory ourSessionFactory;
    //private static final ServiceRegistry serviceRegistry;

    static {
        try {
            Configuration configuration = new Configuration();
            configuration.configure();

            //serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
            ourSessionFactory = configuration.buildSessionFactory();
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static Session getSession() throws HibernateException {
        return ourSessionFactory.openSession();
    }

    public static void main(final String[] args) throws Exception {
        //1.Hibernate 自身的一级缓存，可以查看到只输出了一条 sql
        Session session = getSession();
        UserPO userPO = session.get(UserPO.class, "031e7a36972e11e6acede16e8241c0fe");
        System.out.println("1. 第一次获取对象:" + userPO.getName() + "," + userPO.getPasswd());

        UserPO userPO1 = session.get(UserPO.class, "031e7a36972e11e6acede16e8241c0fe");
        System.out.println("2. 第二次获取对象:" + userPO1.getName() + ",一级缓存中是否存在特定对象" + session.contains(userPO));


        //2.使用 evite/clear 方法手动清除缓存中特定对象，可以看到 hiber 输出了两条 SQL
        Session session1 = getSession();
        UserPO userPO3 = session1.get(UserPO.class, "031e7a36972e11e6acede16e8241c0fe");
        System.out.println("3. 第一次获取对象:" + userPO3.getName() + "," + userPO3.getPasswd());

        session1.evict(userPO3);

        UserPO userPO4 = session1.get(UserPO.class, "031e7a36972e11e6acede16e8241c0fe");
        System.out.println("4. 第二次获取对象:" + userPO4.getName() + "," + userPO4.getPasswd());
    }
}